package com.bcx.crm.plat.core.manage;

import com.bcx.crm.plat.core.utils.SpringContextHolder;
import com.bcx.crm.plat.core.database.DynamicDataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**事物管理器
 * Created by ys on 2017/12/14.
 */
public class TXManage {
    private static DataSourceTransactionManager transactionManager;
    private static DynamicDataSource dataSource;

    /**
     * 需要事物,有则加入,没有则创建
     * @param operate 操作
     */
    public static void doInRequiredTX(TXManage.QNNOperate operate){
        TXManage.doInTx(operate,0);
    }

    private static void doInTx(TXManage.QNNOperate operate,int PROPAGATION){
        if (null!=operate && init()){
            DefaultTransactionDefinition def=new DefaultTransactionDefinition();
            def.setPropagationBehavior(PROPAGATION);
            def.setIsolationLevel(2);
            TransactionStatus status = transactionManager.getTransaction(def);
            try {
                operate.operator(transactionManager,status);
                if (!status.isCompleted()){
                    transactionManager.commit(status);
                }
            } catch (Exception var5) {
                if (!status.isCompleted()){
                    transactionManager.rollback(status);
                }
                throw new RuntimeException(var5);
            }
        }
    }

    /**
     * 初始化本类
     * @return 返回
     */
    private static boolean init(){
        if (null ==transactionManager){
            transactionManager= SpringContextHolder.getBean(DataSourceTransactionManager.class);
        }
        if (null == dataSource){
            dataSource=SpringContextHolder.getBean(DynamicDataSource.class);
        }
        return true;
    }
    @FunctionalInterface
    public interface QNNOperate{
        void operator(PlatformTransactionManager var1, TransactionStatus var2)throws Exception;
    }
}
